package com.flyqiu.flow.core.var;

import com.alibaba.fastjson2.JSONObject;
import com.flyqiu.flow.api.script.IVarSerialize;
import com.flyqiu.flow.api.script.FlyQiuFlowVarSerializeManage;
import com.flyqiu.flow.api.script.VarSerialize;

import java.util.List;

public class BeanConverter implements IVarSerialize {

    private static final String BEAN_CLASS_KEY = "startBeanClass";
    private static final String TYPE_KEY = Object.class.getName();

    @Override
    public String type() {
        return TYPE_KEY;
    }

    @Override
    public boolean isType(FlyQiuFlowVarSerializeManage manage, Object val) {
        if (manage == null) {
            return false;
        }
        List<? extends IVarSerialize> converters = manage.converters();
        return converters.stream().noneMatch(e -> {
            if (e.equals(this)) {
                return false;
            }
            return e.isType(null, val);
        });
    }

    @Override
    public VarSerialize serialize(FlyQiuFlowVarSerializeManage manage, Object val) {
        String clazzName = val.getClass().getName();
        JSONObject from = JSONObject.from(val);
        from.put(BEAN_CLASS_KEY, clazzName);
        return new VarSerialize(TYPE_KEY, from.toJSONString(), false);
    }

    @Override
    public Object deserialize(FlyQiuFlowVarSerializeManage manage, String val) {
        JSONObject object = JSONObject.parseObject(val);
        if (!object.containsKey(BEAN_CLASS_KEY)) {
            throw new RuntimeException("The data has been illegally modified :" + val);
        }
        String clazzName = object.getString(BEAN_CLASS_KEY);
        Class<?> clazz = null;
        try {
            clazz = Class.forName(clazzName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return object.toJavaObject(clazz);
    }

}
